<template>
    <div class="box">
        <div class="card-container">
            <el-row :gutter="10">
                <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
                    <el-col :span="19" :offset="0">
                        <el-form-item label="资料编码" prop="dataCode">
                            <el-input v-model="queryParams.dataCode" placeholder="请输入资料编码" clearable size="small"
                                @keyup.enter.native="handleQuery" />
                        </el-form-item>
                        <!-- <el-form-item label="上传类型" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择上传类型">
                  <el-option label="上传通知" value="3">
                  </el-option>
                  <el-option label="上传滚动消息" value="4">
                  </el-option>
                </el-select>
              </el-form-item> -->
                        <el-form-item label="创建时间" prop="createTime">
                            <el-date-picker clearable size="small" :style="'width:215px'" v-model="queryParams.createTime"
                                range-separator="-" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期"
                                value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5" :offset="0">
                        <el-form-item>
                            <el-button icon="el-icon-search" size="mini" @click="handleQuery">搜索
                            </el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
        </div>

        <!-- <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button   icon="el-icon-plus" size="mini" v-hasPermi="['dataManage:add']"
            @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button   icon="el-icon-delete" size="mini" :disabled="multiple"
            v-hasPermi="['dataManage:remove']" v-show="!multiple" @click="handleDelete">删除</el-button>
        </el-col>
      </el-row> -->
        <div class="card-container">
            <div class="body-title">
                <div class="body-title-left">
                    资料管理
                </div>
                <div class="body-title-right">
                    <el-button icon="el-icon-plus" size="mini" v-hasPermi="['dataManage:add']"
                        @click="handleAdd">新增</el-button>
                    <el-button icon="el-icon-delete" size="mini" :disabled="multiple" v-hasPermi="['dataManage:remove']"
                        v-show="!multiple" @click="handleDelete">删除</el-button>
                    <!-- <el-button  size="mini" :disabled="single" v-show="!multiple" @click="handleUpdate">
              修改</el-button> -->
                    <!-- <el-button  size="mini" :disabled="multiple" v-hasPermi="['dataManage:remove']"  v-show="!multiple"
              @click="handleDelete">删除</el-button> -->
                    <!-- <el-button  size="mini" v-show="!multiple" @click="handleExport">导出</el-button> -->
                    <!-- <el-button   icon="el-icon-plus" v-hasPermi="['dataManage:add']" size="mini" @click="handleAdd">新增
            </el-button> -->
                </div>
            </div>
            <el-table v-loading="loading" ref="table" height="500" :data="dmList" :row-key="getRowKeys"
                @selection-change="handleSelectionChange">
                <!-- :selectable="checkSelectable" -->
                <el-table-column type="selection" width="55" :reserve-selection="true" align="center" />
                <el-table-column label="资料编码" width="180" show-overflow-tooltip align="center" prop="dataCode" />
                <el-table-column label="资料描述" align="left" prop="dataDesc" />
                <el-table-column label="上传类型" align="center" prop="type">
                    <template slot-scope="scope">
                        <span>{{ formatType(scope.row.type) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="发布次数" width="150" align="center" show-overflow-tooltip prop="publishCount" />
                <el-table-column label="操作人" width="150" show-overflow-tooltip align="center" prop="createBy" />
                <el-table-column label="创建时间" width="160" show-overflow-tooltip align="center" prop="createTime" />
                <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <!-- <el-button size="mini" type="text" @click="handlePush(scope.row,'详情')">
                详情</el-button> -->
                        <el-button size="mini" type="text" v-hasPermi="['dataManage:query']"
                            @click="handleDetails(scope.row)">
                            详情</el-button>
                        <!-- <el-button size="mini" type="text" icon="el-icon-delete"
                @click="handleDelete(scope.row)" >删除
              </el-button> -->
              <el-button size="mini" type="text" v-hasPermi="['dataPushTotalLog:query']"
              @click="handlePush(scope.row)">
              推送</el-button>
            <el-button size="mini" type="text" v-hasPermi="['dataPushTotalLog:add']"
              @click="handleUpdateLog(scope.row, '资料推送')">
             记录</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>

        <!-- 添加或修改设备版本对话框 -->
        <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="800px" append-to-body>
            <div class="card-container">
                <el-row :gutter="20">
                    <el-form ref="form" style="max-height: 600px;overflow-y: auto;" :model="form" :rules="rules"
                        label-width="80px">
                        <!-- <el-form-item label="资料编码" prop="dataCode">
            <el-input v-model="form.dataCode" placeholder="请输入资料编码" />
          </el-form-item> -->
                        <el-col :span="24" :offset="0">
                            <el-form-item label="资料描述" prop="dataDesc">
                                <el-input v-model="form.dataDesc" maxlength="100" :style="'width:420px;'"
                                    placeholder="请输入资料描述" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" :offset="0">
                            <el-form-item label="所属项目" prop="projectId">
                                <el-select v-model="form.projectId" clearable :style="'width:420px;'" placeholder="请选择所属项目">
                                    <el-option v-for="item in projectList" :key="item.projectId" :label="item.shortName"
                                        :value="item.projectId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" :offset="0">
                            <el-form-item label="上传类型" prop="type">
                                <el-select v-model="form.type" :style="'width:420px;'" placeholder="请选择上传类型">
                                    <el-option label="上传通知" value="3">
                                    </el-option>
                                    <el-option label="上传滚动消息" value="4">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <div v-if="form.type == 3">
                            <el-col :span="16" :offset="0">
                                <div v-if="!informUrl">
                                    <el-form-item label="通知" prop="">
                                        <!-- <el-upload :action="upload.url" :auto-upload="false" multiple :limit="1"
                  :on-change="handeFileInfo" accept=".jpg,.jpeg,.png"
                  :file-list="upload.info.infoList">
                  <el-button size="small" icon="el-icon-upload2">点击上传</el-button>
                  <span style="margin-left: 10px;color: #C0C4CC;" slot="tip">支持扩展名: .jpg, .jpeg,
                    .png</span>
                </el-upload> -->
                                        <el-button size="small" v-if="!informUrl" icon="el-icon-s-tools"
                                            @click="informVisible">设置</el-button>
                                        <span v-if="!informUrl" style="margin-left: 10px;color: #C0C4CC;">设置后生成图片格式上传</span>
                                    </el-form-item>
                                </div>
                                <div v-if="informUrl">
                                    <el-form-item label="通知" style="position: relative;">
                                        <div
                                            style="width: 200px;margin-left: 10px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                                            {{ form.noticeSourceName }}</div>
                                        <el-image :style="`width: ${108 * 2}px; height: ${80 * 2}px;margin: 0 10px;`"
                                            :src="informUrl" :fit="'fill'"></el-image>
                                        <!-- <el-button v-show="informUrl" style="position: absolute;top:10px;right:50px;"  icon="el-icon-close" size="mini" circle></el-button> -->
                                        <i @click="informRemove"
                                            style="position: absolute;top:10px;left: 52%;width:20px;height:20px;cursor: pointer;color:#ccc;"
                                            class="el-icon-close"></i>
                                    </el-form-item>
                                </div>
                            </el-col>
                            <el-col :span="8" :offset="0">
                                <el-form-item label-width="0px">
                                    <el-input v-model.number="form.noticeDisplayDuration" type="number"
                                        @keyup.native="proving($event)" class="input" placeholder="显示时长">
                                        <template slot="append">分钟</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </div>
                        <div v-if="form.type == 4">
                            <el-col :span="16" :offset="0">
                                <el-form-item label="滚动消息" class="label" prop="">
                                    <el-input v-model="form.scrollMessage" class="input" :style="'width:420px;'"
                                        placeholder="请输入消息文本" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" :offset="0">
                                <el-form-item label-width="0px">
                                    <el-input v-model.number="form.scrollMessageDisplayDuration" type="number"
                                        @keyup.native="proving($event)" class="input" placeholder="显示时长">
                                        <template slot="append">分钟</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </div>
                    </el-form>
                </el-row>
            </div>
            <div slot="footer" class="dialog-footer" style="position: relative;">
                <el-button :loading="submitLoad" @click="submitForm">确 定</el-button>
                <el-button :disabled="submitLoad" @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 详情 -->
        <el-dialog :title="title" :close-on-click-modal="false" v-if="detailsOpen" :visible.sync="detailsOpen" width="800px"
            append-to-body>
            <form-details :form="detailsData" :projectList="projectList"></form-details>
        </el-dialog>

        <!-- 推送记录 -->
        <el-dialog :title="'推送记录'" :close-on-click-modal="false" v-if="updateLogOpen" :visible.sync="updateLogOpen"
            width="800px" append-to-body>
            <update-log :row="updateList" @handleCheck="handleCheck" />
        </el-dialog>

        <!-- 推送失败设备列表 -->
        <el-dialog :title="failTitle" :close-on-click-modal="false" v-if="updateFailOpen" :visible.sync="updateFailOpen"
            width="900px" append-to-body>
            <update-fail :row="updateFailList" />
        </el-dialog>

        <!-- 推送升级 -->
        <el-dialog :title="pushTitle" :close-on-click-modal="false" v-if="updatePushOpen" :visible.sync="updatePushOpen"
            width="800px" append-to-body>
            <update-push :row="updatePushList" :name='pushTitle' @push="handlePushSchedule"
                @cancel="updatePushOpen = false" />
        </el-dialog>

        <!-- 推送升级进度 -->
        <el-dialog :title="'推送升级进度'" :close-on-click-modal="false" v-if="pushScheduleOpen" :visible.sync="pushScheduleOpen"
            width="800px" append-to-body>
            <push-schedule @close="pushScheduleOpen = false" :row="pushScheduleList" />
        </el-dialog>

        <!-- 通知设置 -->
        <inform @informClose="informOpen = false" ref="inform" @submit="informSubmit" v-show="informOpen"
            :informOpen="informOpen" />
    </div>
</template>
  
<script>
import { getListInfo, addData, delData, informPush } from '@/api/dm/dm';
import { getProject } from "@/api/runningLog/runningLog.js";
import updateLog from '../updateLog.vue';
import updateFail from '../updateFail.vue';
import updatePush from '../updatePush.vue';
import pushSchedule from '../pushSchedule.vue';
import inform from '../inform.vue';
import formDetails from '../formDetails.vue';
import ImgCutter from 'vue-img-cutter';
import video from '@/assets/images/video1.png';

export default {
    name: 'dm',
    dicts: ['sys_file_type', 'sys_update_mode', 'sys_normal_disable'],
    components: {
        updatePush,
        pushSchedule,
        updateFail,
        updateLog,
        inform,
        ImgCutter,
        formDetails,
    },
    data() {
        return {
            videoImage: video,
            detailsData: {},
            detailsOpen: false,
            imageUrl: null,
            informOpen: false,
            pushTitle: '资料推送',
            failTitle: '推送失败设备列表',
            submitLoad: false,
            file: {},
            projectList: [],
            upload: {
                url: '',
                video: {
                    videoList: [],
                    file: null,
                },
                audio: {
                    audioList: [],
                    file: null,
                },
                img: {
                    imgList: [],
                    file: null,
                },
                info: {
                    infoList: [],
                    file: null,
                },
            },
            informUrl: null,
            pushScheduleOpen: false,
            pushScheduleList: {},
            updatePushOpen: false,
            updatePushList: {},
            updateFailOpen: false,
            updateFailList: {},
            updateList: {},
            updateLogOpen: false,
            options: [],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 设备版本表格数据
            dmList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                version: null,
                createTime: null,
                dataCode: null,
                type: '3,4',
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                dataDesc: [
                    { required: true, message: '资料描述不能为空', trigger: 'blur' },
                ],
                projectId: [
                    { required: true, message: '所属项目不能为空', trigger: 'change' },
                ],
            },
        };
    },
    created() {
        this.getList();
        this.getProject()
    },
    activated() {
        this.getList();
    },
    methods: {
        // checkSelectable(row) {
        //   return row.publishCount <= 0;
        // },
        async getProject() {
            const res = await getProject();
            if (res.code == 200) {
                this.projectList = res.data;
            }
        },
        formatType(val) {
            switch (val) {
                case '1':
                    return '视频';
                case '2':
                    return '图片';
                case '3':
                    return '通知';
                case '4':
                    return '滚动信息';
                case '5':
                    return '音频';
                default:
                    break;
            }
        },
        async cutDown(event) {
            this.imageUrl = event.dataURL;
            if (event.file.size <= 1024 * 1024 * 5) {
                this.upload.img.file = event.file;
                await this.uploadFun(this.upload.img.file, 'picture');
            } else {
                this.$modal.msgError('上传图片大小不能超过5M');
                this.$refs.imageRef.clearFiles();
            }
            // console.log(event.dataURL);
        },
        async informSubmit(url, name) {
            // console.log(url);
            this.$refs.inform.close();
            this.informUrl = url;
            this.form.noticeSourceName = name;
            let res = await informPush({ inform: url });
            if (res.code == 200) {
                this.form.noticeHdfsName = res.data.fileUrl;
            }
        },
        imageRemove() {
            this.form.pictureHdfsName = null;
            this.form.pictureSourceName = null;
            this.imageUrl = null;
        },
        informRemove() {
            this.form.noticeHdfsName = null;
            this.form.noticeSourceName = null;
            this.informUrl = null;
        },
        informVisible() {
            this.informOpen = true;
        },
        getRowKeys(row) {
            return row.dataManageId;
        },
        proving(e) {
            let keynum = window.event ? e.keyCode : e.which;
            let keychar = String.fromCharCode(keynum);
            if (keynum == 189 || keynum == 190 || keynum == 110 || keynum == 109) {
                // return
                console.log(e.target.value);
                e.target.value = e.target.value;
            }
        },
        handleVideoSuccess(res, file) {
            console.log(res, 'res111111')
            return                            //获取上传图片地址
            this.videoFlag = false;
            this.videoUploadPercent = 0;
            if (res.status == 200) {
                this.videoForm.videoUploadId = res.data.uploadId;
                this.videoForm.Video = res.data.uploadUrl;
            } else {
                this.$message.error('视频上传失败，请重新上传！');
            }
        },
        async handeFileVideo(file, fileList) {
            // this.form.url =URL.createObjectURL(file)
            if (file.size <= 1024 * 1024 * 500) {
                this.upload.video.file = file;
                const reader = new FileReader();
                reader.readAsDataURL(file.raw);
                reader.onload = () => {
                    console.log(reader.result, 'reader.result')
                    this.file.url = reader.result;
                };
                await this.uploadFun(this.upload.video.file.raw, 'video');

            } else {
                this.$modal.msgError('上传视频大小不能超过500M');
                this.$refs.videoRef.clearFiles();
            }
        },
        handeRemoveVideo() {
            this.upload.video.file = null;
            this.upload.video.videoList = [];
            this.form.videoSourceName = null;
            this.form.videoHdfsName = null;
        },
        handleAudioSuccess(res, file) {
            console.log(res, 'res2222')
        },
        async handeFileAudio(file, fileList) {
            // this.form.url =URL.createObjectURL(file)
            if (file.size <= 1024 * 1024 * 500) {
                this.upload.audio.file = file;
                const reader = new FileReader();
                reader.readAsDataURL(file.raw);
                reader.onload = () => {
                    console.log(reader.result, 'reader.result')
                    this.file.url = reader.result;
                };
                await this.uploadFun(this.upload.audio.file.raw, 'warningAudio');

            } else {
                this.$modal.msgError('上传视频大小不能超过500M');
                this.$refs.audioRef.clearFiles();
            }
        },
        handeRemoveAudio() {
            this.upload.audio.file = null;
            this.upload.audio.videoList = [];
            this.form.warningAudioSourceName = null;
            this.form.warningAudioHdfsName = null;
        },
        async handeFileImg(file, fileList) {
            if (file.size <= 1024 * 1024 * 5) {
                this.upload.img.file = file;
                await this.uploadFun(this.upload.img.file.raw, 'picture');
            } else {
                this.$modal.msgError('上传图片大小不能超过5M');
                this.$refs.imageRef.clearFiles();
            }
        },
        removeFileImg(file, fileList) {
            this.form.pictureHdfsName = null;
            this.form.pictureSourceName = null;
        },
        async handeFileInfo(file, fileList) {
            this.upload.info.file = file;
            await this.uploadFun(this.upload.info.file.raw, 'notice');
        },
        handlePushSchedule(row, toData) {
            this.pushScheduleList = {
                row,
                toData,
            };
            this.pushScheduleOpen = true;
        },
        handlePush(row, name) {
            this.updatePushList = row;
            this.pushTitle = name;
            this.updatePushOpen = true;
        },
        handleUpdateLog(row) {
            this.updateList = row;
            this.updateLogOpen = true;
        },
        handleCheck(row, sta) {
            this.updateFailList = row;
            if (sta == '0') {
                this.updateFailList.upgradeStatus = sta;
                this.failTitle = '推送失败设备列表';
            } else {
                this.updateFailList.upgradeStatus = '';
                this.failTitle = '推送设备列表';
            }
            this.updateFailOpen = true;
        },
        /** 查询设备版本列表 */
        getList() {
            this.loading = true;
            getListInfo(this.queryParams).then((response) => {
                this.dmList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                projectId: null,
                dataDesc: null, //资料描述
                warningAudioHdfsName: null, //音频在hdfs中的名称
                videoHdfsName: null, //视频在hdfs中的名称
                pictureHdfsName: null, //图片在hdfs中的名称
                noticeHdfsName: null, //通知在hdfs中的名称
                videoSourceName: null, //视频原文件名
                warningAudioSourceName: null, //音频原文件名
                pictureSourceName: null, //图片原文件名称
                noticeSourceName: null, //通知原文件名称
                noticeDisplayDuration: null, //通知显示时长
                scrollMessage: null, //滚动消息
                scrollMessageDisplayDuration: null, //滚动消息显示时长
            };
            this.upload = {
                url: '',
                video: {
                    videoList: [],
                    file: null,
                },
                audio: {
                    audioList: [],
                    file: null,
                },
                img: {
                    imgList: [],
                    file: null,
                },
                info: {
                    infoList: [],
                    file: null,
                },
            };
            this.informUrl = null;
            this.imageUrl = null;
            this.resetForm('form');
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm');
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.dataManageId);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();

            this.open = true;
            this.submitLoad = false;
            this.title = '新增';
        },
        handleDetails(row) {
            this.cancel();
            this.detailsData = row;
            this.title = '详情';
            this.detailsOpen = true;
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const dataManageId = row.dataManageId || this.ids;
            getVersion(dataManageId).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = '详情';
            });
        },
        async uploadFun(file, name) {
            console.log(name, 'name')
            const formData = new FormData();
            formData.append('file', file);
            this.submitLoad = true;
            this.form[`${name}SourceName`] = file.name;
            console.log(formData, 'formData')
            const res = await this.$api.handelUpload(formData);
            if (res.code == 200) {
                this.submitLoad = false;
                this.form[`${name}HdfsName`] = res.data.filename;
            }
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate(async (valid) => {
                if (valid) {
                    if (this.form.dataManageId == null) {
                        this.submitLoad = true;
                        if (
                            this.form.videoHdfsName !== null ||
                            this.form.pictureHdfsName !== null ||
                            this.form.noticeHdfsName !== null ||
                            this.form.scrollMessage !== null ||
                            this.form.warningAudioHdfsName !== null
                        ) {
                            // this.form.noticeDisplayDuration =
                            //   +this.form.noticeDisplayDuration * 60 * 60;
                            // this.form.scrollMessageDisplayDuration =
                            //   +this.form.scrollMessageDisplayDuration * 60 * 60;
                            console.log(this.form, 'this.form')
                            addData(this.form).then((response) => {
                                this.$modal.msgSuccess('新增成功');
                                this.submitLoad = false;
                                this.open = false;
                                this.getList();
                            });
                        } else {
                            this.submitLoad = false;
                            this.$modal.msgWarning(
                                '视频、音频、图片、通知、滚动消息四个内容必填一个。'
                            );
                        }
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.dataManageId || this.ids;
            this.$modal
                .confirm('是否确认删除？')
                .then(function () {
                    return delData(ids);
                })
                .then(() => {
                    this.$refs.table.clearSelection()
                    this.getList();
                    this.$modal.msgSuccess('删除成功');
                })
                .catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'version/version/export',
                {
                    ...this.queryParams,
                },
                `version_${new Date().getTime()}.xlsx`
            );
        },
    },
};
</script>
  
<style lang="scss" scoped>
.box {
    width: 100%;
    height: 100%;
    padding: 20px;
}

::v-deep .dialogMainModal {
    top: 20px;
}

.body-title {
    display: flex;
    position: relative;
    // justify-content: space-between;
    align-items: center;
}

.body-title-left {
    height: 100%;
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 600;
    color: #fff;
    line-height: 64px;
}

.body-title-right {
    position: absolute;
    right: 0;
}

::v-deep .label {
    position: relative;

    >.el-form-item__label {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }
}

::v-deep .el-input__inner {
    padding-right: 0px;
}</style>
  